<?php

use DateTimeInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class dianpuModel extends Model
{
    use SoftDeletes;

    protected $table = 'dianpu';
    protected $primaryKey = 'id';
    protected $appends = ['status_name'];
    protected $hidden = [];

    /**
     * @param DateTimeInterface $date
     * @return string
     */
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public function getStatusNameAttribute($value)
    {
        $status_name = '禁用';

        if ($this->attributes['status'] > 0) {
            $status_name = '正常';
        }

        return $status_name;
    }

    /**
     * @param float $money 变更金额,正数，根据变更类型自行判断 加/减
     * @param int|object $dianpu 店铺对象或店铺ID
     * @param string $event 变更类型
     * @return boolean
     * @throws Exception
     */
    public static function moneyWithdrawFreeze($money, $dianpu, $event = '')
    {
        // 判断用户
        if (is_numeric($dianpu)) {
            $user_id = $dianpu;
        } else {
            $user_id = $dianpu->id;
        }
        $dianpuModel = dianpuModel::where('id', $user_id)->lockForUpdate()->first();
        if (!$dianpuModel) {
            throw new Exception('未找到店铺');
        }
        // 判断金额是否为0
        if (bccomp($money, 0, 2) <= 0) {
            throw new Exception('请输入正确的金额');
        }
        $money = bcadd(0, abs($money), 2);
        $allEvent = ['dianpuwithdrawapply', 'dianpuwithdrawdenied', 'dianpuwithdrawfinished', 'dianpuwithdrawcanceled'];
        if(!in_array($event, $allEvent)){
            throw new Exception('非法事件');
        }
        //事件标识, dianpuwithdrawapply=店铺提现申请 +, dianpuwithdrawdenied=店铺提现退回 -, dianpuwithdrawfinished=店铺提现完成 -, dianpuwithdrawcanceled=取消提现 -
        $allowSubArray = ['dianpuwithdrawdenied', 'dianpuwithdrawfinished', 'dianpuwithdrawcanceled'];
        if (in_array($event, $allowSubArray)) {
            $after = bcsub($dianpuModel->money_withdraw_freeze, $money, 2);
            if(bccomp($after, 0, 2) < 0){
                throw new Exception("店铺{$user_id}冻结的余额不足");
            }
        }else{
            $after = bcadd($dianpuModel->money_withdraw_freeze, $money, 2);
        }
        try {
            $dianpuModel->money_withdraw_freeze = $after;
            $dianpuModel->save();
        } catch (Exception $e) {
            throw new Exception('您提交的数据不正确');
        }

        return true;
    }

    public function member()
    {
        return $this->belongsTo(\memberModel::class, 'member_id', 'id')->select(['id', 'phone', 'nickname', 'realname', 'avatar']);
    }

    public function dianpuwithdraw()
    {
        return $this->hasMany(dianpuwithdrawModel::class, 'dianpu_id', 'id');
    }

}